import { RouteRecordRaw, createWebHashHistory, createRouter } from "vue-router";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import { usePermissionStore } from "@/store/permission"
import { useUserStore } from "@/store/user"
import { constantRoutes } from "./modules/constant_routes";

// 引入路由模块 组合路由信息 开启懒加载 eager
const modules: Record<string, any> = import.meta.glob("./modules/*.ts", { eager: true });

// 异步路由
export const asyncRoutes: Array<RouteRecordRaw> = [];
Object.keys(modules).forEach((key) => {
  const module = modules[key].default;
  if (module && module.path) {
    asyncRoutes.push(module);
  }
});

// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
});

const whiteList = ['/login', '/error'];

nprogress.configure({ showSpinner: false });

// 路由守卫
router.beforeEach(async (_to, _from, next) => {
  nprogress.start();
  const userStore = useUserStore();
  const permissionStore = usePermissionStore();
  const hasToken = userStore.accessToken;

  if (hasToken) {
    if (_to.path === '/login') {
      next({ path: '/' })
      nprogress.done();
    } else {
      const hasPermissions = userStore.permissions && !!userStore.permissions.length;
      if (hasPermissions) {
        // 检查动态路由是否已添加
        if (!permissionStore.addRoutes.length) {
          try {
            // 重新生成动态路由
            const accessedRoutes = await permissionStore.generateRoutes(userStore.permissions);
            accessedRoutes.forEach(route => {
              router.addRoute(route);
            });
            // 确保路由表更新后重新导航
            return next({ path: _to.path, replace: true, query: _to.query });
          } catch (error) {
            console.error('Failed to regenerate routes:', error);
            userStore.accessToken = ''; // 清空无效 token
            next(`/login?redirect=${_to.path}`);
            nprogress.done();
            return;
          }
        }
        next()
      } else {
        try {
          // 获取用户信息和权限
          const res = await userStore.storeGetUserInfo();
          // 根据权限生成路由
          const accessedRoutes = await permissionStore.generateRoutes(res!.permissions);
          accessedRoutes.forEach(route => {
            router.addRoute(route)
          })
          return next({ path: _to.path, replace: true, query: _to.query });
        } catch (error) {
          userStore.accessToken = ''; // 清空无效 token
          next(`/login?redirect=${_to.path}`)
          nprogress.done();
        }
      }
    }
  } else {
    if (whiteList.indexOf(_to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${_to.path}`);
      nprogress.done();
    }
  }
});
router.afterEach(() => {
  nprogress.done();
});

export default router;
